package com.example.demo.redis.repository;

import com.example.demo.model.Material;
import com.example.demo.redis.mapper.RedisMapper;
import com.example.demo.util.Result;
import com.example.demo.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/12/27.
 */
@Component
public class RedisRepository {

    @Autowired
    private RedisMapper redisMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<Material> queryMaterials(Integer id) {

        String rediskey = "queryMaterials"+id;

        List<Material> queryMaterials = (List<Material>)redisTemplate.opsForValue().get(rediskey);
        if (queryMaterials==null){
            System.out.println("我操作数据库了");
            queryMaterials = redisMapper.queryMaterials(id);
            redisTemplate.opsForValue().set(rediskey,queryMaterials,1, TimeUnit.DAYS);
        }else {
            System.out.println("我操作缓存了");
        }

        return queryMaterials;
    }

    public Result<List<Material>> updateMaterialById(Material material) {

        String rediskey = "queryMaterials"+material.getId();

        //先操作数据库
        redisMapper.updataMaterial(material);
        //把修改完的数据 添加到Redis中
        redisMapper.queryMaterialById(material.getId());
        redisTemplate.opsForValue().set(rediskey,material);
        return ResultVo.success(material);
    }

    public void deleteMaterialById(Integer id) {

        String rediskey = "queryMaterials"+id;

        //先操作数据库
        redisMapper.deleteMaterialById(id);
        //把修改完的数据 添加到Redis
        redisTemplate.delete(rediskey);

    }
}
